package cn.tedu.csmall.product.config;

import cn.tedu.csmall.product.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    /**
     * 创建一个BCryptPasswordEncoder对象
     * @return
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*super.configure(http);*///父方法不调用
        //白名单
        String[] urls={
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
        };

        http.authorizeRequests()
                .antMatchers(urls)//匹配某些路径
                .permitAll()//允许此前匹配的路径直接访问，不需要经过认证或授权

                /*.antMatchers(HttpMethod.OPTIONS,"/**")//匹配某些路径
                .permitAll()//允许此前匹配的路径跳过预检*/

                .anyRequest()//除了以上配置过的其他任何路径
                .authenticated();//需要经过认证

        //允许跨域访问(与50-51行代码作用相同)
        http.cors();//激活Spring Security框架内置的一个CorsFilter，允许跨域访问

        // 关于防伪造的跨域攻击，默认只针对POST / PUT / DELETE / PATCH请求
        /*http.csrf();// 防伪造的跨域攻击*/
        http.csrf().disable();//禁止防伪造的跨域攻击

        //将JWT过滤器添加在Sprint Security的UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);



        /*http.formLogin();*/
    }

}
